package com.lhkk.inventoryvehicle

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.core.content.ContextCompat
import com.cj.mvvmlib.base.viewmodel.BaseViewModel
import com.cj.mvvmlib.ext.util.GsonInstance
import com.cj.mvvmlib.util.ToastUtil
import com.lhkk.inventoryvehicle.ai.VehicleState
import com.lhkk.inventoryvehicle.common.GlobalVariables
import com.lhkk.inventoryvehicle.common.LogFileUtils
import com.lhkk.inventoryvehicle.common.Sm4Decrypt
import com.lhkk.inventoryvehicle.common.Sm4Encrypt
import com.lhkk.inventoryvehicle.common.TimeUtil
import com.lhkk.inventoryvehicle.entity.CarEntity
import com.lhkk.inventoryvehicle.entity.FileUrlRes
import com.lhkk.inventoryvehicle.entity.IsOutStockRes
import com.lhkk.inventoryvehicle.entity.UpImageFinishRequestModel
import com.lhkk.inventoryvehicle.entity.UploadImageRes
import com.lhkk.inventoryvehicle.http.API
import com.lhkk.inventoryvehicle.http.FILE
import com.lhkk.inventoryvehicle.http.RequestUtil
import com.lhkk.inventoryvehicle.http.ResponseBean
import com.lhkk.inventoryvehicle.http.handler
import com.lhkk.inventoryvehicle.http.http
import com.lhkk.inventoryvehicle.http.parseObject
import org.json.JSONException
import org.json.JSONObject
import org.tensorflow.lite.task.vision.detector.Detection
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale

class MainViewModel : BaseViewModel() {

    private var enableTakingPicture: Boolean = false

    companion object {
        private const val TAG = "MainViewModel"
    }

    /**
     * 验证通行权限
     */
    fun verifyPassageAuthority(rfidCode: String, callback: (String, String) -> Unit) {
        val jsonObject = JSONObject()
        try {
            jsonObject.put("uid", rfidCode)
        } catch (e: JSONException) {
            e.printStackTrace() // 处理异常，例如返回 null 或抛出 RuntimeException
        }
        val rfidUUID = jsonObject.toString()
        Log.d(TAG, "${API.REQUEST_PERMISSIONS}加密前数据: $rfidUUID")
        val dataSm4Encrypt = Sm4Encrypt.encryptCbc(API.KEY, rfidUUID)
        Log.d(TAG, "${API.REQUEST_PERMISSIONS}加密后数据: $dataSm4Encrypt")

        http {
            body = RequestUtil.createRequestJson(dataSm4Encrypt)
            url = API.getBaseUrl() + API.REQUEST_PERMISSIONS
            success = {
                it?.let {
                    val sm4Data = parseObject<ResponseBean<String>>(it).data
                    sm4Data?.let {
                        val json = Sm4Decrypt.decryptCbc(API.KEY, sm4Data) //解密
                        val isOutStock = parseObject<IsOutStockRes>(json)
                        callback(isOutStock.inStockStatus, isOutStock.vin)
                    }
                }

            }
            fail = { code, message ->
                ToastUtil.showShortToast(message)
            }
        }
    }

    /**
     * 获取文件上传连接
     */
    fun getUploadUrl(callback: (fileUrlRes: FileUrlRes?) -> Unit) {
        val jsonObject = JSONObject()
        try {
            jsonObject.put("organization", API.ORGANIZATIONAL_CODE)
        } catch (e: JSONException) {
            e.printStackTrace() // 处理异常，例如返回 null 或抛出 RuntimeException
        }
        val data = jsonObject.toString()
        Log.d(TAG, "${API.FILE_UP_URL}加密前数据: $data")
        val dataSm4Encrypt = Sm4Encrypt.encryptCbc(API.KEY, data)
        Log.d(TAG, "${API.FILE_UP_URL}加密后数据: $dataSm4Encrypt")
        http {
            url = API.getBaseUrl() + API.FILE_UP_URL
            body = RequestUtil.createRequestJson(dataSm4Encrypt)
            success = {
                val responseBean = parseObject<ResponseBean<String>>(it).data
                responseBean?.let {
                    val json = Sm4Decrypt.decryptCbc(API.KEY, responseBean) //解密
                    val fileUrlRes = parseObject<FileUrlRes>(json)
                    callback(fileUrlRes)
                }
            }
            fail = { code, message ->
                Log.d(TAG, "获取文件上传连接失败: $message")
            }
        }
    }

    /**
     * 图片上传
     * @param fileUrl 文件上传链接
     * @param t 文件上传凭证
     */
    fun uploadImage(fileSource: File,
        fileUrl: String,
        token: String,
        callback: (key: String?) -> Unit) {
        http {
            file = fileSource
            requestType = FILE
            fileParams.add(Pair("token", token))
            url = fileUrl
            success = {
                it?.let {
                    val result = parseObject<UploadImageRes>(it)
                    callback(result.key)
                }
            }
            fail = { code, message ->
            }
        }
    }

    /**
     * 图片上传完成
     */
    fun uploadImageFinish(key: String,
        requestId: String,
        fileName: String,
        callback: (String) -> Unit) {
        val upImageFinishRequestModel = UpImageFinishRequestModel()
        upImageFinishRequestModel.iobsKey = key
        upImageFinishRequestModel.requestId = requestId
        upImageFinishRequestModel.fileName = fileName
        val data = GsonInstance.getInstance().gson.toJson(upImageFinishRequestModel)
        Log.d(TAG, "${API.FILE_UP_URL}加密前数据: $data")
        val dataSm4Encrypt = Sm4Encrypt.encryptCbc(API.KEY, data)
        Log.d(TAG, "${API.FILE_UP_URL}加密后数据: $dataSm4Encrypt")
        http {
            body = RequestUtil.createRequestJson(dataSm4Encrypt)
            url = API.getBaseUrl() + API.FILE_UP_FINISH
            success = {
                val sm4Result = parseObject<ResponseBean<String>>(it).data
                sm4Result?.let {
                    val json = Sm4Decrypt.decryptCbc(API.KEY, sm4Result) //解密
                    val jsonObject = JSONObject(json)
                    val result = jsonObject.getString("resId")
                    callback(result)
                }
            }
            fail = { code, message ->
            }
        }
    }

    /**
     * 同步出库信息
     */
    fun synchronizeOutStockInfo(carEntity: CarEntity?, callback: () -> Unit) {
        val stringTime = TimeUtil.timestamp2String(System.currentTimeMillis())
        carEntity?.inOutStatusTime = stringTime
        val carJson = GsonInstance.getInstance().gson.toJson(carEntity)
        LogFileUtils.writeTxtToFile("执行数据同步：$carJson")
        Log.d(TAG, "${API.IN_OUT_SYNC}加密前数据: $carJson")
        val sm4Data = Sm4Encrypt.encryptCbc(API.KEY, carJson)
        Log.d(TAG, "${API.IN_OUT_SYNC}加密前数据: $carJson")
        http {
            url = API.getBaseUrl() + API.IN_OUT_SYNC
            body = RequestUtil.createRequestJson(sm4Data)
            success = {
                Log.d(TAG, "同步出库信息成功")
                LogFileUtils.writeTxtToFile("数据同步执行成功")
                callback()
            }
            fail = { code, message ->
                Log.d(TAG, "同步出库信息失败: $message")
                LogFileUtils.writeTxtToFile("数据同步执行失败: $code-$message")
                callback()
            }
        }
    }

    fun takePhoto(cameraType: Int,
        stateName: String,
        imageCapture: ImageCapture?,
        context: Context) {
        if (!enableTakingPicture) {
            return
        }
        val filename = "${stateName}_$cameraType.jpeg"
        val path = GlobalVariables.getImagePath()
        val photoFile = File(path, filename)

        val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()

        imageCapture?.takePicture(outputOptions,
            ContextCompat.getMainExecutor(context), // Use main executor for callback
            object : ImageCapture.OnImageSavedCallback {
                override fun onError(exc: ImageCaptureException) {
                    Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
                    handler.post {
                        Toast.makeText(context, "图片保存失败: ${exc.message}", Toast.LENGTH_SHORT)
                            .show()
                        when (stateName) {
                            VehicleState.APPROACHING.name -> {
                                ToastUtil.showShortToast("车头图片保存失败")
                                LogFileUtils.writeTxtToFile("车头图片保存失败")
                            }
                            VehicleState.CENTERED.name -> {
                                ToastUtil.showShortToast("车身图片保存失败")
                                LogFileUtils.writeTxtToFile("车身图片保存失败")
                            }
                            VehicleState.DONE.name -> {
                                ToastUtil.showShortToast("车尾图片保存失败")
                                LogFileUtils.writeTxtToFile("车尾图片保存失败")
                            }
                        }
                    }
                }

                override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                    val msg = "图片保存成功: ${output.savedUri}"
                    Log.d(TAG, msg)
                    handler.post {
                        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                        when (stateName) {
                            VehicleState.APPROACHING.name -> {

                                MainActivity.frontImagePath.postValue(photoFile.absolutePath)
                                LogFileUtils.writeTxtToFile("车头图片保存成功")
                                Log.d(TAG, "车头图片保存成功到: ${photoFile.absolutePath}")
                                ToastUtil.showShortToast("车头图片保存成功到: ${photoFile.absolutePath}")
                            }
                            VehicleState.CENTERED.name -> {

                                MainActivity.bodyImagePath.postValue(photoFile.absolutePath)
                                LogFileUtils.writeTxtToFile("车身图片保存成功")
                                Log.d(TAG, "车身图片保存成功到: ${photoFile.absolutePath}")
                                ToastUtil.showShortToast("车身图片保存成功到: ${photoFile.absolutePath}")
                            }
                            VehicleState.DONE.name -> {

                                MainActivity.rearImagePath.postValue(photoFile.absolutePath)
                                LogFileUtils.writeTxtToFile("车尾图片保存成功")
                                Log.d(TAG, "车尾图片保存成功到: ${photoFile.absolutePath}")
                                ToastUtil.showShortToast("车尾图片保存成功到: ${photoFile.absolutePath}")
                            }
                        }
                    }
                }
            })
    }

    /**
     * 是否执行拍照
     */
    fun isEnablePhoto(enable: Boolean) {
        LogFileUtils.writeTxtToFile("允许拍照")
        enableTakingPicture = enable
    }
}
